package com.chuck.blogpro.fliter;

import com.alibaba.fastjson.JSONObject;
import com.chuck.blogpro.pojo.Result;
import com.chuck.blogpro.utils.JWTUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;

// http 请求过滤器
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();

        if (uri.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String jwt = request.getHeader("token");

        if (!StringUtils.hasLength(jwt)){
            log.info("请求头token为空");
            Result objc = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(objc);
            response.getWriter().write(jsonString);
            return;
        }

        // 校验
        Map<String, Object> map = JWTUtils.checkToken(jwt);


        if (map == null){
            log.info("token已过期");
            Result objc = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(objc);
            response.getWriter().write(jsonString);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
